package com.example.springpethospital.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.springpethospital.entity.IDAndName;

import java.util.Date;

public class TokenUtil {
    public static final int EXPIRE_SECONDS = 24 * 3600;
    private static final String TOKEN_SECRET = "aff82db490851d2e";

    public static String sign(String username, Integer userid) {
        Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_SECONDS * 1000L);
        String token = JWT.create()
                .withIssuer("auth0")
                .withClaim("username", username)
                .withClaim("userid", userid)
                .withExpiresAt(expiresAt)
                .sign(Algorithm.HMAC256(TOKEN_SECRET));
        return token;
    }

    public static IDAndName verify(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
            DecodedJWT jwt = verifier.verify(token);
            String username = jwt.getClaim("username").asString();
            Integer id = jwt.getClaim("userid").asInt();
            return new IDAndName(id, username);
        } catch (JWTVerificationException e) {
            return null;
        }
    }
}